package org.example.service.impl;

import org.example.dao.IProductDao;
import org.example.entity.ProductEntity;
import org.example.exception.UserException;
import org.example.service.IProductService;
import org.example.util.PageRecord;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author HanJiafeng
 */
@Service
public class ProductServiceImpl implements IProductService {
    private final IProductDao productDao;

    public ProductServiceImpl(IProductDao productDao) {
        this.productDao = productDao;
    }

    @Override
    public ProductEntity getById(Integer id) throws UserException {
        try {
            return productDao.selectById(id);
        } catch (IOException e) {
            throw new UserException("查询产品异常", e);
        }
    }

    @Override
    public PageRecord<List<ProductEntity>> listAllByCid(Integer cid, Integer currentPage, Integer pageSize) throws UserException {
        ProductEntity productEntity = new ProductEntity();
        productEntity.setCid(cid);
        try {
            List<ProductEntity> productEntityList = productDao.selectSelective(productEntity, null, null);
            //获取商品的数量
            int count = productEntityList.size();
            //计算总页数
            Integer pageCount = (count - 1) / pageSize + 1;
            //计算分页查询的起始值
            Integer recordIndex = (currentPage - 1) * pageSize;
            List<ProductEntity> data = productDao.selectSelective(productEntity, recordIndex, pageSize);
            return new PageRecord<>(pageSize, count, pageCount, currentPage, data);
        } catch (IOException e) {
            throw new UserException("查询商品异常", e);
        }
    }
}
